package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.tanhua.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IMService imService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0") // 2.0.0是es关于查找位置的实现，1.0.0是Mongodb关于查找位置的实现
    private UserLocationApi userLocationApi;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUser;

    @Value("${tanhua.sso.url}")
    private String url;

    /**
     * 查询今日佳人
     *
     * @return
     */
    public TodayBest queryTodayBest() {
        //查询当前的登录信息
        User user = UserThreadLocal.get();

        //查询今日佳人
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId()); // id,得分
        if (todayBest == null) {
            // 默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
        }
        //补全信息
        UserInfo userInfo = this.userInfoService.findById(todayBest.getId());
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * @return
     */
    public PageResult queryPageResult(RecommendUserQueryParam queryParam) {
        // 查询当前登录的用户信息
        User user = UserThreadLocal.get();
        // 根据用户id进行分页查询
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        // 推荐用户列表
        List<RecommendUser> records = pageInfo.getRecords();
        // 如果列表为空，使用默认推荐的用户
        if (CollectionUtils.isEmpty(records)) {
            String[] strings = StringUtils.split(defaultRecommendUser, ',');
            for (String string : strings) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(string));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));
                records.add(recommendUser);
            }
        }
        // 封装推荐用户的id
        List<Long> ids = new ArrayList<>();
        for (RecommendUser recommendUser : records) {
            ids.add(recommendUser.getUserId());
        }

        // 构造查询用户信息的条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", ids);

        /*if (StringUtils.isNotEmpty(queryParam.getGender())) { //性别条件
            if (queryParam.getGender().equals("man")) {
                queryWrapper.eq("sex", 1);
            } else {
                queryWrapper.eq("sex", 2);
            }
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) { //居住城市
            queryWrapper.eq("city", queryParam.getCity());
        }

        if (queryParam.getAge() != null) { //年龄
            queryWrapper.lt("age", queryParam.getAge());
        }*/

        List<UserInfo> userInfos = userInfoService.queryList(queryWrapper);

        // 封装完善TodayBest信息
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = getTodayBest(userInfo);
            // 设置缘分值
            for (RecommendUser recommendUser : records) {
                if (todayBest.getId().longValue() == recommendUser.getUserId().longValue()) {
                    double score = Math.floor(recommendUser.getScore()); //取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }

        // 对推荐用户根据缘分值进行排序
        todayBestList.sort((o1, o2) -> (int) (o2.getFateValue() - o1.getFateValue()));
        return new PageResult(0, queryParam.getPagesize(), 0, queryParam.getPage(), todayBestList);
    }

    /**
     * 查询佳人信息
     *
     * @param id
     * @return
     */
    public TodayBest queryTodayBestInfo(Long id) {
        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryById(id);
        todayBest.setId(id);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(id, user.getId());
        if (score == 0) {
            score = 98; //默认分值
        }
        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    /**
     * 查询陌生人问题
     *
     * @param userId
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryById(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            // 把消息转为json字符串
            String msgStr = MAPPER.writeValueAsString(msg);
            // 构建url：sso中向环信发送消息的接口
            String targetUrl = this.url + "/user/huanxin/messages";
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            // 设置请求体
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);
            // 封装请求头和请求体
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);
            // 发送请求
            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    /**
     * 搜附近
     *
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();

        // 获取用户信息的对象，然后获得经纬度
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        // 根据当前用户的位置信息查询附近的好友
        List<UserLocationVo> userLocationVoList = this.userLocationApi.queryUserFromLocation(longitude, latitude, Integer.parseInt(distance));
        if (CollectionUtils.isEmpty(userLocationVoList)) {
            return null;
        }

        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            userIds.add(locationVo.getUserId());
        }
        //根据id列表查找用户信息
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            query.in("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            query.in("sex", SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryList(query);

        // 遍历集合，把NearUserVo添加到集合
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            // 排除自己
            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();

                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());

                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }
        return nearUserVoList;
    }

    /**
     * 探花卡片
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        // 默认查询50条数据
        int count = 50;
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);

        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            String[] strings = StringUtils.split(defaultRecommendUser, ',');
            for (String string : strings) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(string));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));
                records.add(recommendUser);
            }
        }

        // 设置10个推荐的卡片
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecords = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            createRecommendUserList(records,newRecords);
        }

        // 查询用户信息
        List<Long> ids = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            ids.add(record.getUserId());
        }

        // 构造查询用户信息的条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", ids);
        List<UserInfo> userInfos = userInfoService.queryList(queryWrapper);

        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = getTodayBest(userInfo);
            todayBest.setFateValue(0L);
            todayBestList.add(todayBest);

        }
        return todayBestList;
    }

    /**
     * 封装todayBest对象
     *
     * @param userInfo 用户信息
     * @return
     */
    private TodayBest getTodayBest(UserInfo userInfo) {
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userInfo.getUserId());
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        return todayBest;
    }

    /**
     * 递归生成好友，保证不重复
     *
     * @param records
     * @param newRecords
     */
    private void createRecommendUserList(List<RecommendUser> records, List<RecommendUser> newRecords) {
        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0, records.size() - 1));
        if (!newRecords.contains(recommendUser)) {
            newRecords.add(recommendUser);
        } else {
            // 开始递归
            createRecommendUserList(records,newRecords);
        }
    }

    /**
     * 右划喜欢
     *
     * @param likeUserId 喜欢的用户id
     * @return 成功true，失败false
     */
    public boolean saveUserLike(Long likeUserId) {
        User user = UserThreadLocal.get();

        String result = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        Boolean mutualLike = this.userLikeApi.isMutualLike(user.getId(), likeUserId);

        // 将喜欢的状态存到redis
        String redisKey = "USER" + user.getId() + "LIKE" + likeUserId;
        this.redisTemplate.opsForValue().set(redisKey,"1");

        if (mutualLike){
            // 如果互相喜欢，则成为好友
            this.imService.contactUser(likeUserId);
        }
        return StringUtils.isNotEmpty(result);
    }

    /**
     * 左划不喜欢
     *
     * @param likeUserId 不喜欢的用户id
     * @return 状态码：200 | 500
     */
    public boolean deleteUserLike(Long likeUserId) {
        User user = UserThreadLocal.get();

        Boolean result = this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
        if (result){
            // 将喜欢的状态从redis中删除
            String redisKey = "USER_" + user.getId() + "LIKE_" + likeUserId;
            this.redisTemplate.delete(redisKey);
        }
        return result;
    }
}
